package com.cooba.content_frament;

import android.animation.Animator;
import android.animation.AnimatorInflater;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.cooba.R;
import com.cooba.activitys.RedWalletDetailsActivity;
import com.cooba.activitys.login.LoginActivity;
import com.cooba.application.MyApplication;
import com.cooba.bean.RedWalletBean;
import com.cooba.dialog.RedWalletDialog;
import com.cooba.news_frament.AmusementFrament;
import com.cooba.news_frament.HotpointFrament;
import com.cooba.news_frament.LifeFrament;
import com.cooba.news_frament.LiteratureFrament;
import com.cooba.news_frament.SocietyFrament;
import com.cooba.utils.CommonUtil;
import com.cooba.utils.Rotate3DNumberAnimation;
import com.cooba.utils.ServerURL;
import com.cooba.utils.SharedPreferencesUtil;
import com.cooba.views.GlideRoundTransform;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Administrator on 2015/12/7.
 * 新闻
 */
public class HomeFrament extends Fragment {

    private static String[] titles = new String[]{"热点", "社会", "娱乐", "生活", "美文"};

    private ArrayList<Fragment> fragList;
    private ViewPager mViewPager;

    private MyTabFragmentAdapter mAdapter;
    private RedWalletDialog dialog;
    private HttpUtils httpUtils;
    private RequestParams params;
    private MyApplication application;
    private FrameLayout home_fl;
    private RedWalletBean redwalletbean;
    private AnimationDrawable animationDrawable;
    private ImageView iv;
    private ObjectAnimator rotationAnimator;
    private boolean flag=false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Nullable
    private View contentview;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        if (contentview == null) {
            contentview = initview(inflater);
        }
        //缓存的rootView需要判断是否已经被加过parent， 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
        ViewGroup parent = (ViewGroup) contentview.getParent();
        if (parent != null) {
            parent.removeView(contentview);
        }
        return contentview;
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        getRedWallet();
    }

    private void getRedWallet() {
        httpUtils = new HttpUtils();
        //params = new RequestParams();
        httpUtils.send(HttpRequest.HttpMethod.POST, ServerURL.httpUrl + ServerURL.showredwallet, new RequestCallBack<String>() {
            @Override
            public void onFailure(HttpException arg0, String arg1) {
                Log.e("wei", "获取失败");
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.e("wei", "获取成功" + responseInfo.result);
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(responseInfo.result.toString());
                    String result = jsonObject.get("status").toString();
                    String msg = jsonObject.get("msg").toString();
                    if (result.equals("1")) {
                        String beginTime = jsonObject.get("firstTime").toString();
                        String endTime = jsonObject.get("lastTime").toString();
                        if (!TextUtils.isEmpty(beginTime) || !TextUtils.isEmpty(endTime)) {
                            startTimer(beginTime, endTime);
                            //createView();
                        } else {
                            createView();
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void startTimer(String beginTime, String endTime) {
        try {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date currenttime = new Date();
            String currentdatestr = formatter.format(currenttime);
            String currentdatestr1 = formatter1.format(currenttime);
            beginTime = currentdatestr + " " + beginTime;
            endTime = currentdatestr + " " + endTime;
            Date currentdate = formatter1.parse(currentdatestr1);
            //Date currentdate = formatter1.parse("2016-09-06 12:59:30");
            Date begindate = formatter1.parse(beginTime);
            Date enddate = formatter1.parse(endTime);
            if (currentdate.getTime() >= begindate.getTime() && currentdate.getTime() <= enddate.getTime()) {
                createView();
            } else if (currentdate.getTime() < begindate.getTime()) {
                long temp=begindate.getTime()-currentdate.getTime();
                new Timer(true).schedule(new TimerTask() {
                    @Override
                    public void run() {
                        myhandler.sendEmptyMessage(1);
                    }
                }, temp);
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    private Handler myhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    createView();
                    break;
                default:
                    break;
            }
        }
    };

    private void createView() {
        ImageView tip=new ImageView(getContext());
        //tip.setImageResource(R.mipmap.qian);
        Glide.with(getActivity()).load(R.mipmap.qian).transform(new GlideRoundTransform(getContext(),14)).into(tip);
        FrameLayout.LayoutParams lp=new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT);
        lp.gravity=Gravity.RIGHT|Gravity.CENTER;
        tip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showRedWalletDialog();
            }
        });
        home_fl.addView(tip, lp);

    }



    private void showRedWalletDialog() {
        dialog = new RedWalletDialog(getActivity(), R.style.custom_dialog1, R.layout.red_wallet_dialog, null, new RedWalletDialog.DialogListener() {
            @Override
            public void getRedWallet(View v) {
                iv= (ImageView) v;
                String login_id=SharedPreferencesUtil.getData(getContext(),"login_id","");
                if (!TextUtils.isEmpty(login_id)) {
                    doOpenRedWallet(login_id);
                }else {
                    showWarnDialog();
                    dialog.dismiss();
                }
            }
        });
        dialog.setCanceledOnTouchOutside(true);
        android.view.Window window = dialog.getWindow();
        window.setGravity(Gravity.CENTER);
        dialog.show();
    }
    public void showWarnDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setTitle("尚未登录,是否登录?");
        builder.setNegativeButton("否", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();

            }
        });
        builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(getContext(), LoginActivity.class);
                startActivity(intent);
            }
        });
        AlertDialog dialog = builder.create();
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();

    }
    private void doOpenRedWallet(String user_id) {
        startAnimation();
        httpUtils = new HttpUtils();
        params = new RequestParams();
        params.addBodyParameter("user_id", user_id);
        httpUtils.send(HttpRequest.HttpMethod.POST, ServerURL.httpUrl + ServerURL.getredwallet, params, new RequestCallBack<String>() {
            @Override
            public void onFailure(HttpException arg0, String arg1) {
                Log.e("wei", "获取失败");
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.e("wei", "获取成功" + responseInfo.result);
                try {
                    redwalletbean = new Gson().fromJson(responseInfo.result, RedWalletBean.class);
                    flag = true;
                    //gotodetail();
//                    if (redwalletbean.getStatus().equals("1")) {
//                        initData();
//                    }
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                }
//                JSONObject jsonObject = null;
//                try {
//                    jsonObject = new JSONObject(responseInfo.result.toString());
//                    String result = jsonObject.get("status").toString();
//                    String msg = jsonObject.get("msg").toString();
//                    //if (result.equals("1")) {
//                    //String dbmoney = jsonObject.get("dbMoney").toString();
//                    //Toast.makeText(getActivity(), "领取红包：" + dbmoney, Toast.LENGTH_SHORT).show();
//                    gotodetail();
//                    //}else {
//                    //    Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
//                    //}
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
            }
        });
    }

    private void startAnimation() {
        rotationAnimator = ObjectAnimator.ofFloat(iv, "RotationY", 0, 360);
        rotationAnimator.setDuration(1000);
        rotationAnimator.setRepeatCount(ObjectAnimator.RESTART);
        rotationAnimator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                iv.setClickable(false);
                Log.d("wei", "animationstart");
            }

            @Override
            public void onAnimationRepeat(Animator animation) {
                Log.d("wei", "animationrepeat");
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                Log.d("wei", "animationend");
                if (flag) {
                    dialog.dismiss();
                    gotodetail();
                }
            }
        });
        setCameraDistance();
        rotationAnimator.start();
    }
    private void setCameraDistance() {
        int distance = 6000;
        float scale = getResources().getDisplayMetrics().density * distance;
        iv.setCameraDistance(scale);
        //llyBack.setCameraDistance(scale);
    }

    private void gotodetail() {
        dialog.dismiss();
        Intent intent = new Intent(getContext(), RedWalletDetailsActivity.class);
        intent.putExtra("redwallet",redwalletbean);
        startActivity(intent);
    }


    //初始化控件
    private View initview(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.home_frament, null, false);
        home_fl= (FrameLayout) view.findViewById(R.id.home_fragment_fl);
        mViewPager = (ViewPager) view.findViewById(R.id.mViewPager_home);
        // 初始化
        initFragment();
        mAdapter = new MyTabFragmentAdapter(fragList, titles, getFragmentManager(), getContext());
        mViewPager.setAdapter(mAdapter);
        // 将ViewPager和TabLayout绑定
        TabLayout tablayout = (TabLayout) view.findViewById(R.id.tablayout_home);
        tablayout.setupWithViewPager(mViewPager);

        return view;
    }


    /**
     * Created by lt on 2015/12/14.
     */
    public class MyTabFragmentAdapter extends FragmentPagerAdapter {

        private final String[] titles;
        private Context context;
        private List<Fragment> fragments;

        public MyTabFragmentAdapter(List<Fragment> fragments, String[] titles, FragmentManager fm, Context context) {
            super(fm);
            this.context = context;
            this.fragments = fragments;
            this.titles = titles;
        }


        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return titles.length;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return titles[position];
        }
    }


    /**
     * 初始化 Fragment
     */
    public void initFragment() {
        fragList = new ArrayList<Fragment>();

        //HotpointFrament_New fragment1 = new HotpointFrament_New();
        HotpointFrament fragment1 = new HotpointFrament();
        SocietyFrament fragment2 = new SocietyFrament();

        AmusementFrament fragment3 = new AmusementFrament();

        LifeFrament fragment4 = new LifeFrament();

        LiteratureFrament fragment5 = new LiteratureFrament();

        fragList.add(fragment1);
        fragList.add(fragment2);
        fragList.add(fragment3);
        fragList.add(fragment4);
        fragList.add(fragment5);
//        fragList.add(fragment6);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        Log.d("wei--", "Home:" + isVisibleToUser);

    }
//    @Override
//    public void onDestroyView() {
//        super.onDestroyView();
//        for (int i=0;i<fragList.size();i++) {
//            if (fragList.get(i) != null) {
//                FragmentManager f = getFragmentManager();
//                if (f != null && !f.isDestroyed()) {
//                    final FragmentTransaction ft = f.beginTransaction();
//                    if (ft != null) {
//                        ft.remove(fragList.get(i)).commit();
//                    }
//                }
//            }
//        }
//    }
}
